package com.futao.springbootlearn20220224.redis.scan;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author futao@gmail.com
 * @date 2022/4/14
 */
@Slf4j
@RequestMapping("/redis/scan")
@RestController
public class ZSetScanDemo {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/zset")
    public void set() {
        stringRedisTemplate.delete("scan:zset");
        log.info("start save data");
        Set<ZSetOperations.TypedTuple<String>> typedTuples = IntStream.rangeClosed(1, 10000)
                .mapToObj(x -> {
                    String s = String.valueOf(x);
                    return new DefaultTypedTuple<>("s" + s, (double) x);
                }).collect(Collectors.toSet());

        Long add = stringRedisTemplate.opsForZSet().add("scan:zset", typedTuples);
        log.info("end save data: {}", add);

        log.info("start scan zset");
        ScanOptions scanOptions = ScanOptions.scanOptions()
                .count(1000)
                .build();
        Cursor<ZSetOperations.TypedTuple<String>> scan = stringRedisTemplate.opsForZSet().scan("scan:zset", scanOptions);
        log.info("end scan set {}", scan.stream().count());
    }
}
